package com.platform.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.util.wechat.MD5;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpClient4.3工具类
 *
 * @author hang.luo
 */
public class HttpClientUtils {

  private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录

  private static RequestConfig requestConfig = null;

  static {
    // 设置请求和传输超时时间
    requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
  }

  /**
   * post请求传输json参数
   *
   * @param url url地址
   */
  public static JSONObject httpPost(String url, JSONObject jsonParam) {
    // post请求返回结果
    CloseableHttpClient httpClient = HttpClients.createDefault();
    JSONObject jsonResult = null;
    HttpPost httpPost = new HttpPost(url);
    // 设置请求和传输超时时间
    httpPost.setConfig(requestConfig);
    try {
      if (null != jsonParam) {
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
      }
      CloseableHttpResponse result = httpClient.execute(httpPost);
      // 请求发送成功，并得到响应
      if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String str = "";
        try {
          // 读取服务器返回过来的json字符串数据
          str = EntityUtils.toString(result.getEntity(), "utf-8");
          // 把json字符串转换成json对象
          jsonResult = JSONObject.parseObject(str);
        } catch (Exception e) {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    } catch (IOException e) {
      logger.error("post请求提交失败:" + url, e);
    } finally {
      httpPost.releaseConnection();
    }
    return jsonResult;
  }

  /**
   * post请求传输String参数 例如：name=Jack&sex=1&type=2 Content-type:application/x-www-form-urlencoded
   *
   * @param url url地址
   * @param strParam 参数
   */
  public static JSONObject httpPost(String url, String strParam) {
    // post请求返回结果
    CloseableHttpClient httpClient = HttpClients.createDefault();
    JSONObject jsonResult = null;
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    try {
      if (null != strParam) {
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(strParam, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(entity);
      }
      CloseableHttpResponse result = httpClient.execute(httpPost);
      // 请求发送成功，并得到响应
      if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String str = "";
        try {
          // 读取服务器返回过来的json字符串数据
          str = EntityUtils.toString(result.getEntity(), "utf-8");
          // 把json字符串转换成json对象
          jsonResult = JSONObject.parseObject(str);
        } catch (Exception e) {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    } catch (IOException e) {
      logger.error("post请求提交失败:" + url, e);
    } finally {
      httpPost.releaseConnection();
    }
    return jsonResult;
  }

  /**
   * 发送get请求
   *
   * @param url 路径
   */
  public static JSONObject httpGet(String url) {
    // get请求返回结果
    JSONObject jsonResult = null;
    CloseableHttpClient client = HttpClients.createDefault();
    // 发送get请求
    HttpGet request = new HttpGet(url);
    request.setConfig(requestConfig);
    try {
      CloseableHttpResponse response = client.execute(request);

      // 请求发送成功，并得到响应
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // 读取服务器返回过来的json字符串数据
        HttpEntity entity = response.getEntity();
        String strResult = EntityUtils.toString(entity, "utf-8");
        // 把json字符串转换成json对象
        jsonResult = JSONObject.parseObject(strResult);
      } else {
        logger.error("get请求提交失败:" + url);
      }
    } catch (IOException e) {
      logger.error("get请求提交失败:" + url, e);
    } finally {
      request.releaseConnection();
    }
    return jsonResult;
  }
//{"location":{"lng":123.789665,"lat":41.29517},"deviation":1000,"title":"欣丰华园超市","address_components":{"province":"辽宁省","city":"本溪市","street":"","district":"明山区","street_number":""}},"message":"query ok","status":0}
  //"location":{"lng":123.788971,"lat":41.294949}
//  public static void main(String[] args) {
//    String sig = MD5.getMessageDigestNotUpper("/ws/geocoder/v1/?key=HDFBZ-EWTKW-HUNRK-O5N5I-VWYD7-ESFW6&address=辽宁省本溪市明山区金山街道丰华新城欣丰华园超市3m4ccaJJqc1JCNOeuDTboXtnpoQmfGs");
//    System.out.println(sig);
//    String url = "https://apis.map.qq.com/ws/distance/v1/?mode=walking&from=41.29517,123.789665&to=41.294949,123.788971&key=HDFBZ-EWTKW-HUNRK-O5N5I-VWYD7-ESFW6";
//    System.out.println(url);
//
//    JSONObject jsonObject = httpGet(url);
//    JSONObject result = jsonObject.getJSONObject("result");
//    JSONArray elements = result.getJSONArray("elements");
//    for (Object o : elements) {
//      JSONObject jsonObject1 = (JSONObject) o;
//      Integer distance = jsonObject1.getInteger("distance");
//      System.out.println(distance + "米");
//    }
//
//    System.out.println();
//  }


}